package org.andao.commons.lucene.bean;

import java.util.List;
import java.util.Map;

import org.apache.solr.common.SolrDocument;

/**
 * lucene搜索结果Bean，基于Solr的实现
 * 
 * @author Seewo Software - Vick.liu (liuguanglin@cvte.cn)
 * 
 */
public class LuceneResult extends SolrDocument {

	private static final long serialVersionUID = 4235521186339340454L;

	/**
	 * solr搜索返回的结果单元
	 */
	private SolrDocument solrDocument;
	/**
	 * solr搜索返回的高亮结果集
	 */
	private Map<String, Map<String, List<String>>> highlightMap;

	/**
	 * 构造函数，初始化solrdocument和highlightMap
	 * 
	 * @param solrDocument
	 * @param highlightMap
	 */
	public LuceneResult(SolrDocument solrDocument, Map<String, Map<String, List<String>>> highlightMap) {
		this.setSolrDocument(solrDocument);
		this.highlightMap = highlightMap;

	}

	/**
	 * 获取数据(不高亮)
	 * 
	 * @param key
	 * @return
	 */
	public Object get(String key) {
		Object result = solrDocument.getFirstValue(key);
		return result == null ? "" : result;
	}

	/**
	 * 获取数据(如果数据是高亮，则高亮)
	 * 
	 * @param key
	 *            要获取的数据的key
	 * @param indexKey
	 *            solr索引主键
	 * @return
	 */
	public Object get(String key, String indexKey) {
		return getHighlightFieldValue(key, indexKey);
	}

	/**
	 * 获取高亮字段数据
	 * 
	 * @param key
	 *            要获取的数据的key
	 * @param indexKey
	 *            solr索引主键
	 * @return
	 */
	public Object getHighlightFieldValue(String key, String indexKey) {
		// 获取高亮字段
		if (null != highlightMap && highlightMap.containsKey(indexKey)) {
			List<String> highlightListStr = highlightMap.get(indexKey).get(key);
			if (null != highlightListStr && !highlightListStr.isEmpty()) {
				return highlightListStr.get(0);
			}
			return "";
		} else {
			// 如果不是高亮字段，则获取普通字段
			Object result = solrDocument.getFirstValue(key);
			return result == null ? "" : result;
		}
	}

	// --------setter and getter ----------//
	/**
	 * 获取solrDocument
	 * 
	 * @return
	 */
	public SolrDocument getSolrDocument() {
		return solrDocument;
	}

	public void setSolrDocument(SolrDocument solrDocument) {
		this.solrDocument = solrDocument;
	}

}
